<template>
  <a-modal
    :title="title"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    :width="600"
    :maskClosable="false"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :rules="formRules"
    >
      <a-form-item label="客户名称">
        <a-input :value="formData.customerName" disabled />
      </a-form-item>
      
      <a-form-item label="产品类别">
        <a-input :value="formData.productType" disabled />
      </a-form-item>
      
      <a-form-item label="产品名称">
        <a-input :value="formData.productNameDisplay" disabled />
      </a-form-item>
      
      <a-form-item label="最终价格">
        <a-input-number :value="formData.finalAmount" disabled style="width: 100%" />
      </a-form-item>
      
      <a-form-item label="合同主题" name="contractSubject">
        <a-input
          v-model:value="formData.contractSubject"
          placeholder="请输入合同主题"
          :max-length="100"
          show-count
          allow-clear
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose } from 'vue';
import { Form } from 'ant-design-vue';
const useForm = Form.useForm;

const title = ref<string>('生成合同');
const visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formRef = ref();

const emit = defineEmits(['ok']);

const labelCol = reactive({ span: 6 });
const wrapperCol = reactive({ span: 18 });

const formData = reactive({
  // 订单信息
  id: '',
  customerId: '',
  customerName: '',
  followUpId: '',
  productType: '',
  productName: [],
  productNameDisplay: '',
  finalAmount: 0,
  sysUserId: '',
  realName: '',
  // 合同主题
  contractSubject: '',
});

const formRules = reactive({
  contractSubject: [
    { required: true, message: '请输入合同主题', trigger: 'blur' },
    { min: 2, max: 100, message: '合同主题长度应在2-100个字符之间', trigger: 'blur' }
  ]
});

const { validate, resetFields } = useForm(formData, formRules);

/**
 * 显示弹窗
 */
function show(orderRecord: any) {
  visible.value = true;
  
  // 填充订单信息
  Object.assign(formData, {
    id: orderRecord.id,
    customerId: orderRecord.customerId,
    customerName: orderRecord.customerName,
    followUpId: orderRecord.followUpId,
    productType: orderRecord.productType,
    productName: orderRecord.productName,
    productNameDisplay: formatProductNames(orderRecord.productName),
    finalAmount: orderRecord.finalAmount,
    sysUserId: orderRecord.sysUserId,
    realName: orderRecord.realName,
    contractSubject: '', // 清空合同主题
  });
}

/**
 * 格式化产品名称显示
 */
function formatProductNames(productName: any): string {
  if (!productName) return '-';
  
  if (typeof productName === 'string') {
    try {
      const names = JSON.parse(productName);
      return Array.isArray(names) ? names.join(', ') : productName;
    } catch (e) {
      return productName.split(',').map((item: string) => item.trim()).join(', ');
    }
  }
  
  if (Array.isArray(productName)) {
    return productName.join(', ');
  }
  
  return String(productName);
}

/**
 * 确定按钮点击事件
 */
async function handleOk() {
  try {
    await validate();
    confirmLoading.value = true;
    
    // 发送数据到父组件
    emit('ok', {
      ...formData,
      // 确保产品名称是数组格式
      productName: Array.isArray(formData.productName) 
        ? formData.productName 
        : (formData.productName ? String(formData.productName).split(',').map(item => item.trim()) : [])
    });
    
  } catch (error) {
    console.log('表单验证失败:', error);
  } finally {
    confirmLoading.value = false;
  }
}

/**
 * 取消按钮点击事件
 */
function handleCancel() {
  visible.value = false;
  resetFields();
}

/**
 * 关闭弹窗
 */
function close() {
  visible.value = false;
  resetFields();
}

defineExpose({
  show,
  close
});
</script>

<style lang="less" scoped>
.ant-input-number {
  width: 100%;
}
</style>
